import { formatDateTime } from './utils'
import {
  handleAddPerformanceRecord,
  handleUpdateParentPerformanceRecord
} from './preformance_record'

export default function (sqlite) {
  return {
    // 录入业绩
    insertPerformance(
      dealerId,
      dealerName,
      dealerParentId,
      dealerParentName,
      dealerLevelId,
      dealerLevelName,
      performanceDate,
      performanceMoney
    ) {
      return new Promise((resolve, reject) => {
        const sql =
          'INSERT INTO performance (dealer_id,dealer_name,dealer_level_id,dealer_level_name,performance_date,performance_money,create_time,modify_time,parent_dealer_id,parent_dealer_name) VALUES (?, ?, ?, ?, ?, ?, ?, ?,?,?)'
        sqlite.run(
          sql,
          [
            dealerId,
            dealerName,
            dealerLevelId,
            dealerLevelName,
            performanceDate,
            performanceMoney,
            formatDateTime(),
            formatDateTime(),
            dealerParentId,
            dealerParentName
          ],
          async function (err) {
            if (err) {
              console.error('Error inserting dividend:', err.message)
              reject(err.message)
            } else {
              await handleAddPerformanceRecord(
                dealerId,
                dealerName,
                performanceDate,
                performanceMoney,
                sqlite
              )
              await handleUpdateParentPerformanceRecord(dealerId, performanceDate, sqlite)
              resolve(this.lastID)
            }
          }
        )
      })
    },
    // 获取业绩列表
    getPerformanceList(
      pageSize,
      offset,
      startDate = null,
      endDate = null,
      dealerName = null,
      dealerLevelId = null
    ) {
      return new Promise((resolve, reject) => {
        // 基础查询条件
        let baseSql = 'FROM performance WHERE 1=1'
        const params = []

        if (startDate) {
          baseSql += ' AND performance_date >= ?'
          params.push(startDate)
        }
        if (endDate) {
          baseSql += ' AND performance_date <= ?'
          params.push(endDate)
        }

        // 添加 dealer_name 模糊查询条件（如果提供）
        if (dealerName) {
          baseSql += ' AND dealer_name LIKE ?'
          params.push(`%${dealerName}%`)
        }

        // 添加 dealer_level_id 精确查询条件（如果提供）
        if (dealerLevelId) {
          baseSql += ' AND dealer_level_id = ?'
          params.push(dealerLevelId)
        }

        // 构建获取总数的查询
        const countSql = `SELECT COUNT(*) as total ${baseSql}`

        // 构建分页查询（使用 datetime 函数修正排序问题）
        const dataSql = `
          SELECT * ${baseSql} 
          ORDER BY strftime('%s', create_time) DESC 
          LIMIT ? OFFSET ?`
        const dataParams = [...params, pageSize, offset * pageSize] // 分页参数

        // 执行两个查询：一个统计总数，一个获取分页数据
        sqlite.get(countSql, params, (err, countRow) => {
          if (err) {
            console.error('Error counting performance records:', err.message)
            reject(err.message)
          } else {
            const total = countRow.total

            // 查询实际数据
            sqlite.all(dataSql, dataParams, (err, rows) => {
              if (err) {
                console.error('Error fetching performance data:', err.message)
                reject(err.message)
              } else {
                resolve({ total, rows })
              }
            })
          }
        })
      })
    },

    // 获取业绩导出数据
    getPerformanceExport(
      startDate = null,
      endDate = null,
      dealerName = null,
      dealerLevelId = null
    ) {
      return new Promise((resolve, reject) => {
        // 基础查询条件
        let baseSql = 'FROM performance WHERE 1=1'
        const params = []
        if (startDate) {
          baseSql += ' AND performance_date >= ?'
          params.push(startDate)
        }
        if (endDate) {
          baseSql += ' AND performance_date <= ?'
          params.push(endDate)
        }

        // 添加 dealer_name 模糊查询条件（如果提供）
        if (dealerName) {
          baseSql += ' AND dealer_name LIKE ?'
          params.push(`%${dealerName}%`)
        }

        // 添加 dealer_level_id 精确查询条件（如果提供）
        if (dealerLevelId) {
          baseSql += ' AND dealer_level_id = ?'
          params.push(dealerLevelId)
        }

        // 构建查询
        const dataSql = `SELECT * ${baseSql} ORDER BY create_time DESC`
        const dataParams = [...params] // 分页参数

        // 查询实际数据
        sqlite.all(dataSql, dataParams, (err, rows) => {
          if (err) {
            console.error('Error fetching dealer data:', err.message)
            reject(err.message)
          } else {
            resolve({ rows })
          }
        })
      })
    }
  }
}
